<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/12/21 0021
 * Time: 16:28
 */

namespace app\admin\logic;


use think\Db;
use app\admin\model\Order as order_model;
use app\common\traits\Gate;
use think\Validate;

class Order
{
    public $order_model;
    use Gate;
    use \app\common\traits\Common;

    /**获取模型
     * @return Depar_model|string
     */
    public function getModel()
    {
        if (empty($this->order_model)) {
            $this->order_model = new order_model();
        }
        return $this->order_model;
    }

    /**
     * 联系方式排重
     * @param $data
     * @return array|false|\PDOStatement|string|\think\Model
     * @author: Huang
     */
    public function ContactFind($data)
    {
        $order_model = new order_model();
        return $order_model->where($data)->find();
    }

    /**
     * 查询单条数据
     * @param $data
     * @return array|false|\PDOStatement|string|\think\Model
     * @author: Huang
     */
    public static function find($data)
    {
        $res = order_model::where($data)->find();

        $res = $res->append(['state_text', 'jdry_text', 'channel_text', 'channel_path_text', 'source_text', 'yykf_group_text', 'yykf_text', 'leibie_text',
            'intention_text', 'budget_text', 'activity_text', 'mendian_text', 'menshi_text', 'tracking_text', 'track_text', 'nostore_text', 'payment_text',
            'shot_mode_text', 'shot_time_text', 'instoreyy_text', 'photo_grapher_text'])
            ->toArray();
        return $res;
    }

    /**
     * 新增订单
     * @param $data
     * @param int $actionname
     * @return array
     */
    public function add($data, $actionname = 1)
    {

        if ($actionname == 1) {
            $a = new Order();
            $user = session('admin_user');
            $line = '';
            if ($this->hasRole([  'qdzy', 'qdkf'])) {
                if ($this->hasRole('line', $user['adminid'])) {
                    $line = true;
                } else {
                    $line = false;
                }
            } elseif ($this->hasRole([ 'yyzg', 'yyzy'])) {
                if ($this->hasRole('line', $user['adminid'])) {
                    $line = true;
                } else {
                    $line = false;
                }

            }

            if ($line === false) {
                unset($data['xingqi']);
                unset($data['banji']);
                unset($data['shijianduan']);
            }

            $data = $this->addData($data);
        }


        $data['shijianduan'] = $this->time_slot($data['shijianduan']);

        $res = $this->getModel()->validate(true)->allowField(true)->save($data);

//        $res = Db::name('order')->insertGetId($data);

        $orderid = $this->getModel()->getLastInsID();
//        $orderid = $res;
//        dump($orderid);
//        die();
        if (!empty($data['yykf_group']) && !empty($data['yykf'])) {
            //发送邀约发送微信消息
            Wechat::sendWechatToYyry($orderid);
        }

//      成功，更新日志
        if ($res) {
            addOrderLog([
                'actionname' => $actionname,
                'order_id' => $orderid,
                'khd' => 1, 'state' => $data['state']], [],
                $data, 'order');
            return ['status' => '1', 'info' => "数据添加成功"];
        } else {//失败
            return ['status' => '0', 'info' => '数据添加失败:' . $this->getModel()->getError()];
        }
    }

    /**新建订单的补充数据
     * @param $data
     * @return mixed
     */
    public function addData($data)
    {
        $user = session('admin_user');

        if (empty($user['depar_id'])) {  //微信端添加
            $userAll = session('weixinuser');

            $data['jdry'] = $userAll['id'];
            if (empty($data['jd_depar'])) {
                $data['jd_depar'] = $userAll['depar_id'];//建单部门
            }

        } else {
            $data['jdry'] = $user['adminid'];
            if (empty($data['jd_depar'])) {
                $data['jd_depar'] = $user['depar_id'];//建单部门
            }
        }

        $data['jdtime'] = time();//建单时间
        $data['cztime'] = time();//操作时间
        if (empty($data['state'])) {
            $data['state'] = 1;//建单默认待跟进
        }

        if (!empty($data['yykf_group']) && !empty($data['yykf'])) {
            $data['yyfptime'] = time();
            $data['state'] = 2; //已分配
            //发送邀约发送微信消息
//            Wechat::sendWechatToYyry($id);
        }

//        if (!empty($data['yykf'])) {
//            $userinfo = Db::name('users')->where(['id' => $data['yykf'], 'status' => 1])->field('id,ygroup_id')->find();
//            $data['ygroup_id'] = $userinfo['ygroup_id'];
//        }
        return $data;
    }


    /**
     * 更新数据
     * @param $data
     * @param int $actionname 日志操作名称
     * @return array
     * @author: Huang
     */
    public function updata($data, $actionname = 2)
    {
        $id = $data['id'];
        $ordermoder = $this->getModel();
        $olddata = $ordermoder::get($id);
//        //改变订单状态
        if (empty($olddata['yykf']) && !empty($data['yykf'])) {
            if (empty($data['state'])) {
                $data['state'] = 2;
            }
            $data['yyfptime'] = time();
        }
        $data = $this->StateTime($data);
        $data['shijianduan'] = $this->time_slot($data['shijianduan']);
        $res = $this->getModel()->update($data);
        //发送门店微信信息
        if (!empty($data['mendian']) && $data['state'] == 3) {
            Wechat::sendWechatToDz($id);
        }
        //发送门市微信信息
        if (!empty($data['menshi'])) {
            Wechat::sendWechatToMenshi($id);
        }
        //发送摄影师微信信息
        if (!empty($data['photo_grapher'])) {
            Wechat::sendWechatToSheyingshi($id);
        }
        //发送邀约微信消息
        if (empty($olddata['yykf']) && !empty($data['yykf'])) {
            Wechat::sendWechatToYyry($id);
        }

        if ($data['state'] == 4 || $data['state'] == 11 || $data['state'] == 14 || $data['state'] == 15) {
            //发送摄影调度微信信息
            Wechat::sendWechatToDiaodu($id);
            //体验免费发送短信
            if (!empty($data['mendian']) && !empty($data['yypstime'])) {
                $this->sendSms($olddata, $data['mendian'], $data['yypstime']);
            }
        }
//        $oldinstore = $olddata['instore'];
//        $newinstore = $data['instore'];
//        if ($oldinstore == 0 && $newinstore == 1) {
//            Wechat::sendWechatToDz($id);
//        }
        if ($res == false) {
            return ['status' => '0', 'info' => '数据修改失败:' . $this->getModel()->getError()];
        } else {
            unset($data['cztime']);
            $state = empty($data['state']) ? $olddata['state'] : $data['state'];
            addOrderLog([
                'actionname' => $actionname,
                'order_id' => $id,
                'khd' => 1, 'state' => $state
            ], $olddata->toArray(),
                $data, 'order');
            return ['status' => '1', 'info' => '数据修改成功！'];
        }
    }


    /**上课时间段c操作
     * @param $time
     * @return string
     */
    public function time_slot($time){
        if (!empty($time)) {
            $time_slot = explode('-', $time);
            foreach ($time_slot as $k => $v) {
                $time_slot[$k] = explode(':', $v);
            }
            $zhongzhuan = 0;
            foreach ($time_slot as $k => $v) {
                if ($k == 1) {

                } else {
                    if ((int)$time_slot[$k][0] > (int)$time_slot[$k + 1][0]) {
                        if ($k + 1 !== null) {
                            $zhongzhuan = $time_slot[$k];
                            $time_slot[$k] = $time_slot[$k + 1];

                            $time_slot[$k + 1] = $zhongzhuan;
                        }
                    } else if ((int)$time_slot[$k][0] == (int)$time_slot[$k + 1][0]) {
                        if ((int)$time_slot[$k][1] > (int)$time_slot[$k + 1][1]) {
                            if ($k + 1 !== null) {
                                $zhongzhuan = $time_slot[$k];
                                $time_slot[$k] = $time_slot[$k + 1];
                                $time_slot[$k + 1] = $zhongzhuan;
                            }
                        }
                    }
                }
            }
            foreach ($time_slot as $k => $v) {
                $time_slot[$k] = implode(':', $v);
            }
            $time = implode('-', $time_slot);
            return $time;
        }
    }


        /**短信发送
     * @param $olddata
     * @param $store
     * @param $yypstime
     * @return array
     */
    public function sendSms($olddata, $store, $yypstime)
    {
        if (!empty($olddata['phone_z'])) {
            $sendphone = $olddata['phone_z'];
        } else {
            $sendphone = $olddata['phone_f'];
        }
        if ($store == 14) {
            $address = '冉家坝SM店';
//            $address='SM店:冉家坝SM广场3楼纷乐迪主题儿童摄影';
        } elseif ($store == 27) {
            $address = '大坪店';
//            $address='大坪店:渝中区大坪龙湖时代天街时代汇11号写字楼(D馆9号门左斜对面)5楼纷乐迪摄影馆';
        } elseif ($store == 28) {
            $address = '渝中区大坪石油路龙湖时代天街C馆L3-33-34';
        } elseif ($store == 31) {
            $address = '沙坪坝店';
//            $address='沙坪坝店:沙坪坝华宇广场2号时代星空5楼纷乐迪主题儿童摄影，（华宇集团城市展厅旁的观光电梯上5楼）';
        }
        $template = 'SMS_125019330';
        $smsdata = [
            'time' => date("m月d日 H:i", $yypstime),
            'store' => $address,
            'hotline' => '61611831',
        ];
        $re = Sms::sendsms($sendphone, $template, $smsdata);
        return $re;
    }


//    /**
//     *测试发送短信
//     */
//    public function csSendSms(){
//        $sendphone='13110206631';
//        $template='SMS_125019330';
//        $smsdata=[
//            'time'=>date("m月d日 H:i",1515925229),
//            'store'=>'冉家坝SM店',
//            'hotline'=>'61611831',
//        ];
//        $re=Sms::sendsms($sendphone,$template,$smsdata);
//        return $re;
//    }

    /**
     * 假删除数据
     * @param $data
     * @return mixed
     * @author: Huang
     */
    public
    function del($data)
    {
        $res = $this->getModel()->update($data);
        return $res;
    }

    /**
     * 查询权限检测
     * @param $data
     * @return mixed
     * @author: Huang
     */
    public function power($data = null)
    {
        $user = session('admin_user');
        if ($this->hasRole('qdjl')) {
            $useraLL = collect(self::getCommonModel()->getUserByDeparId(1))->pluck('id')->all();
            if (empty($data['jdry'])) {
                $data['jdry'] = ['in', $useraLL];
            }
        } elseif ($this->hasRole('qdzg')) {
            $useraLL = collect(self::getCommonModel()->getUserByDeparId(session('admin_user.depar_id')))->pluck('id')->all();
            if (empty($data['jdry'])) {
                $data['jdry'] = ['in', $useraLL];
            }
        } elseif ($this->hasRole(['qdzy', 'qdkf'])) {
            if ($this->hasRole('line')) {
                $data['jd_depar'] = ['eq', session('admin_user.depar_id')];
            } else {
                $data['jd_depar'] = ['eq', session('admin_user.depar_id')];
            }
        } elseif ($this->hasRole('yyjl')) {
            $useraLL = collect(self::getCommonModel()->getUserByDeparId(3))->pluck('id')->all();
            /*if(empty($data['yykf'])){
                $data['yykf|jdry'] = ['in', $useraLL];
            }*/
        } elseif ($this->hasRole('yyzg')) {
            if (empty($data['yykf_group'])) {
                $data['yykf_group'] = session('admin_user.depar_id');
            }
        } elseif ($this->hasRole('yyzy')) {
            if ($this->hasRole('line')) {
                $data['yykf|jdry'] = ['eq', $user['adminid']];
            } else {
                $data['yykf|jdry'] = ['eq', $user['adminid']];
            }
        } elseif ($this->hasRole('mdjl')) {
            $useraLL = collect(self::getCommonModel()->getSonDepar(2))->pluck('id')->all();
            $data['mendian'] = ['in', $useraLL];
        } elseif ($this->hasRole('mdzg')) {
            $data['mendian'] = ['eq', session('admin_user.depar_id')];
//            $data['menshi'] = ['in', $useraLL];
        } elseif ($this->hasRole('diaodu')) {
            $data['mendian'] = ['eq', session('admin_user.depar_id')];
            $data['state'] = ['in', '4,11,14,15,19,20'];
        } elseif ($this->hasRole(['mdzy', 'sheyingshi'])) {
            $data['menshi'] = ['eq', $user['adminid']];
        }
        return $data;
    }

    /**
     * 各状态时间
     * @param $data
     * @return mixed
     * @author: wu
     */
    public
    function StateTime($data)
    {
        //免费体验时间
        if ($data['state'] == 4) {
            $data['mftytime'] = time();
        }
        //未到流失时间
        if ($data['state'] == 7) {
            $data['yywdlstime'] = time();
        }
        //未到店时间
        if ($data['state'] == 12) {
            $data['wddtime'] = time();
        }
        //无需追踪时间
        if ($data['state'] == 6) {
            $data['wxzztime'] = time();
        }
        //进店流失
        if ($data['state'] == 13) {
            $data['jdlstime'] = time();//进店流失时间
        }
        //进店成交和流回成交
        if ($data['state'] == 13 || $data['state'] == 14 || $data['state'] == 15) {
            $data['ddtime'] = time();//到店时间
        }
        //邀约外拍时间
        if ($data['state'] == 21) {
            $data['yywptime'] = time();
        }
        //拍摄分次时间
        if ($data['state'] == 19) {
            $data['psfctime'] = time();
        }
        //成功拍摄时间
        if ($data['state'] == 20) {
            $data['cgpstime'] = time();
        }
        //线上成交时间
        if ($data['state'] == 11) {
            $data['xscjtime'] = time();
        }
        //进店成交时间
        if ($data['state'] == 14) {
            $data['jdcjtime'] = time();
        }
        //流回成交时间
        if ($data['state'] == 15) {
            $data['lhcjtime'] = time();
        }
        //成交时间
        if ($data['state'] == 4 || $data['state'] == 11 || $data['state'] == 14 || $data['state'] == 15) {
            $data['cjtime'] = time();
        }
        //操作时间
        $data['cztime'] = time();
        return $data;
    }


}